TOP_DIR        ?= $(shell realpath ../)
DESTDIR        ?= $(TOP_DIR)/out
TARGET_BOARD   ?= UNKNOWN

include ../Common.mk
-include ../Config.mk
-include ../ConfigToolchain.mk

libxpr_DEFS     = \
	-DHAVE_MP \
	-DHAVE_PTHREAD_H \
	-DHAVE_SCHED_H \
	-DHAVE_SIGNAL_H \
	-DHAVE_STDINT_H \
	-DHAVE_TIME_H \
	-DHAVE_UNISTD_H \
	-D_DEFAULT_SOURCE \
	-D_GNU_SOURCE \
	-DPIC
libxpr_OBJS     =
libxpr_CFLAGS   = -fPIC
libxpr_CXXFLAGS = -fPIC
libxpr_LDFLAGS  = -shared -Wl,--version-script=libxpr.sym
libxpr_LIBS     =

include Modules.mk

config_FILE = $(TOP_DIR)/include/xpr/xpr_config.h
config_VARS = $(sort $(foreach v,$(sort $(.VARIABLES)),$(filter XPR_%,$v)))

libxpr_CFLAGS   += -include $(config_FILE)
libxpr_CXXFLAGS += -include $(config_FILE)
libxpr_LIBS     += -Wl,-Bdynamic -lstdc++ -lpthread -lm -ldl

CFLAGS      += $(libxpr_CFLAGS) $(libxpr_DEFS)
CXXFLAGS    += $(libxpr_CXXFLAGS) $(libxpr_DEFS)
LDFLAGS     += $(libxpr_LDFLAGS)

targets =
ifeq ($(BUILD_STATIC),y)
targets += libxpr.a
endif
ifeq ($(BUILD_SHARED),y)
targets += libxpr.so
endif

all: prepare $(targets) local_install

prepare: $(config_FILE) $(config_VARS) config_DEFS

libxpr.a: $(libxpr_OBJS)
	$(ECHO) "[  Archive] $@"
	$(AR) crv $@ $^

libxpr.so: $(libxpr_OBJS)
	$(ECHO) "[     Link] $@"
	$(LD) $(LDFLAGS) $^ -o $@ $(libxpr_LIBS)

%.o: %.cpp
	$(ECHO) "[Compiling] $^"
	$(CXX) $(CXXFLAGS) $($(call filter_spc,$^)_CXXFLAGS) -c $^ -o $@

%.o: %.c
	$(ECHO) "[Compiling] $^"
	$(CC) $(CFLAGS) $($(call filter_spc,$^)_CFLAGS) -c $^ -o $@

$(config_FILE):
	@echo "// Auto generated by Makefile" > $@
	@echo "// Date: $$(date)" >> $@
	@echo "" >> $@
	@echo "// Target board" >> $@
	@echo "#define TARGET_BOARD_$(shell echo $(TARGET_BOARD)|tr '[:lower:]' '[:upper:]') 1" >> $@
	@echo "" >> $@

$(config_VARS): $(config_FILE)
	@echo "// $(@)" >> $^; \
	if [ x$($(@)) = xy ]; then \
	  echo "#define HAVE_$@ 1" >> $^; \
	else \
	  echo "#undef HAVE_$@" >> $^; \
	fi; \
	echo "" >> $^; \

config_DEFS: $(config_FILE)
	@for v in $(filter -DHAVE%,$(libxpr_DEFS)); do \
		echo "// $${v#-D} ">> $^; \
		echo "#define $${v#-D} 1" >> $^; \
		echo "" >> $^; \
	done

clean:
	$(RM) $(libxpr_OBJS) $(targets)

install: $(targets)
	$(ECHO) "[Installing] $^"
	$(INSTALL) -d "$(DESTDIR)$(INSTALL_PREFIX)/lib/"
	$(INSTALL) -m 0755 $^ "$(DESTDIR)$(INSTALL_PREFIX)/lib/"

local_install: $(targets)
	$(ECHO) "[  Install] Copy $^ to ../lib/"
	@[ -d ../lib/ ] || mkdir ../lib
	$(CP) $^ ../lib/

strip: libxpr.so
	$(STRIP) $^
	make local_install

.PHONY: $(config_FILE)
